package com.blyat.xsoft.kernel.component.pool;

import org.apache.commons.pool2.ObjectPool;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @Auther: syh
 * @Date: 2020/8/3
 * @Description:
 */
public abstract class AbstractConnection implements Connection {
    private static final Logger logger = LoggerFactory.getLogger(AbstractConnection.class);
    private URL url;
    private State state = State.init;
    private ObjectPool pool;

    public AbstractConnection(URL url, ObjectPool<? extends Connection> pool) {
        this.pool = pool;
        this.url = url;
    }

    @Override
    public boolean isStarted() {
        return State.start == this.state;
    }

    @Override
    public void connect() {
        try {
            doConnect();
            this.state = State.start;
        } catch (Exception e) {
            logger.error("cipher connection:{} connect failed.", this.url, e);
            this.state = State.close;
            try {
                close();
            } catch (Exception ex) {
                // ignore.
            }
        }
    }

    @Override
    public void close() throws Exception {
        if (isStarted()) {
            this.pool.returnObject(this);
        } else {
            this.state = State.close;
            doClose();
        }
    }

    enum State {
        init, start, close;
    }

    protected abstract void doConnect() throws Exception;

    protected abstract void doClose() throws Exception;
}
